extends Node2D

#自身碰撞
onready var collision_shape_2d = $CollisionShape2D
#爆炸碰撞
onready var cs_2dx = $FireArea2D/CS2DX
onready var cs_2dy = $FireArea2D/CS2DY

const dir = { "up": Vector2(0, -1),
			  "down": Vector2(0, 1),
			  "left": Vector2(-1, 0),
			  "right": Vector2(1, 0) }

## 炸弹属性
var cell_pos = Vector2() # 炸弹在tilemap 的坐标
var bomb_range = 0 # 炸弹爆炸范围
var range_len = 0 #炸弹碰撞长度
var fire_pos_array =[] # 火花的位置



func _ready():
	pass

func set_bomb_range(input_range):
	##设置爆炸范围
	bomb_range = input_range


func update_cell_position():
	#保存瓦片位置，以减少涉及的计算，缺点是每次炸弹更换单元格时都必须调用此函数
	cell_pos = GdGlobal.UIBattle.world_to_map(self.get_position())


func set_pos_and_update(abs_pos):
	#设置绝对位置并更新离散瓦片位置
	set_position(abs_pos)
	update_cell_position()

func creater_fire_pos_array():
	#创建火花位置集合
	#中间的位置
	fire_pos_array.append(cell_pos)
	#向上的位置
	for i in bomb_range:
		var new_pos = cell_pos + dir.up * (i+1)
		if check_pos_obstacle(new_pos):
			break
		else:
			fire_pos_array.append(new_pos)
	#向下的位置
	for i in bomb_range:
		var new_pos = cell_pos + dir.down * (i+1)
		if check_pos_obstacle(new_pos):
			break
		else:
			fire_pos_array.append(new_pos)
	#向左的位置
	for i in bomb_range:
		var new_pos = cell_pos + dir.left * (i+1)
		if check_pos_obstacle(new_pos):
			break
		else:
			fire_pos_array.append(new_pos)
	#向右的位置
	for i in bomb_range:
		var new_pos = cell_pos + dir.right * (i+1)
		if check_pos_obstacle(new_pos):
			break
		else:
			fire_pos_array.append(new_pos)
	#print(fire_pos_array)

func check_pos_obstacle(pos):
	# 检查是否障碍遮挡
	if int(pos.x) %2 ==1 and  int(pos.y) %2 ==1 :
		#print("检查位置："+str(pos)+"为双单")
		return true
	elif pos.x <= 7 or pos.x >= 21:
		#print("检查位置："+str(pos)+"为边缘")
		return true
	elif pos.y <= 1 or pos.y >= 15:
		#print("检查位置："+str(pos)+"为边缘")
		return true
	else :
		return false



func _on_Area2D_body_exited(_body):
	#玩家离开区域时，开启碰撞
	collision_shape_2d.set_deferred("disabled",false)
	pass # Replace with function body.

func bomb_boom():
	##炸弹爆炸
	if cell_pos == GdGlobal.UIBattle.old_bomb_pos:
		#清除老坐标
		GdGlobal.UIBattle.old_bomb_pos = Vector2()
	#creater_fire() 会报错，改下面调用
	call_deferred("creater_fire")
	queue_free()

func _on_TimerIdle_timeout():
	bomb_boom()
	pass

func creater_fire():
	#创建火焰
	for i in fire_pos_array:
		var fire = GdGlobal.fire_scene.instance()
		GdGlobal.UIBattle.effects.add_child(fire)
		fire.set_position(GdGlobal.UIBattle.fire_map_to_world(i))

